// @ts-nocheck
const array2approvalTree = (list: any) => {
  const gg = (data: any) => {
    if (data.pointType === 6) {
      return data;
    }
    const { relDescDetail } = data;
    if (typeof relDescDetail !== "object" || !relDescDetail.length) return;
    //判断是否下级关联的是否是条件
    let nextNode = list.find(
      (ele: any) => ele.id === relDescDetail[0].nextStep
    );
    if (!nextNode) return;
    if (nextNode?.pointType === 4) {
      let nextNode2 = list.find(
        (ele: any) => ele.id === relDescDetail[1].nextStep
      );
      //条件要找到同级结束点
      data.childNode = digui(nextNode, nextNode2);
      //找汇合点的下一节点，继续拼接
      if (data.childNode) {
        data.childNode = gg(data.childNode);
      }
      relDescDetail.forEach((detail, index) => {
        if (!data?.conditionNodes) data.conditionNodes = [];
        const conditionNode = list.find(
          (val: any) => val.id === detail.nextStep
        );
        const isExsit = data.conditionNodes.findIndex(
          (cNode: any) => cNode.id === conditionNode.id
        );

        if (isExsit < 0 && conditionNode.pointType === 4) {
          data.conditionNodes.push(conditionNode);
          gg(conditionNode);
          // data.conditionNodes[index].childNode = gg(conditionNode);
        }
      });
      data.conditionNodes.sort((a: any, b: any) => a.priority - b.priority);
    } else {
      // data.childNode = nextNode;
      //如果此节点被记录过，则返回空
      if (flagIds.includes(nextNode.id)) return data;
      flagIds.push(nextNode.id);
      data.childNode = gg(nextNode);
    }
    return data;
  };
  const digui = (child1: any, child2: any) => {
    const result = fact(child1, child2);
    //如果没有找到，继续往下找
    if (!result) {
      const nextId = child2.relDescDetail[0].nextStep;
      if (!nextId) {
        return result;
      }
      const nextNode = list.find((item: any) => item.id === nextId);
      return digui(child1, nextNode);
    } else {
      return result;
    }
  };
  const flagIds = [];
  //找两个节点的汇合节点
  const fact = (child1: any, child2: any) => {
    const nextId = child1.relDescDetail[0].nextStep;
    if (!nextId) return;
    const nextNode = list.find((item: any) => item.id === nextId);
    //如果next同时有child1和child2，则为汇合
    if (nextNode?.relDescDetail.length > 1) {
      //获取节点的所有上节点
      const index1 = nextNode?.relDescDetail.findIndex(
        (val) => val.previousStep === child1.id
      );
      const index2 = nextNode?.relDescDetail.findIndex(
        (val) => val.previousStep === child2.id
      );
      if (index1 > -1 && index2 > -1) {
        //汇合点
        // console.log("汇合", nextNode);
        //如果此节点被记录过，则返回空
        if (flagIds.indexOf(nextId) >= 0) return;
        flagIds.push(nextId);
        return nextNode;
      }
    }
    return fact(nextNode, child2);
  };
  return {
    gg,
  };
};
export default array2approvalTree;
